#!/usr/bin/python3
from plugins.Index import plugins
from utils import My_Util
from utils.ProjectConfigReader import ProjectConfigReader
import os
import pymysql
import shutil
import json


def get_config_from_sheet(sheet, col, return_type=1):
    """
    从工程配置文件中获取配置
    :param col 列数
    :param return_type 返回值类型；1：列表，2：单个元素
    """
    _configs = list()
    _result = None
    for row in sheet.rows:
        if row[col].row < 2:
            continue
        if row[col].value is None:
            break
        if return_type == 1:
            _configs.append(row[col].value)
        elif return_type == 2:
            _result = row[col].value
            break
    if return_type == 1:
        return _configs
    elif return_type == 2:
        return _result


def get_config():
    """
    获取用户配置
    """
    config_filename = ".db_manager.json"
    no_set_file = False
    try:
        with open(
            os.path.join(os.path.expanduser("~"), config_filename),
            mode="r",
            encoding="utf-8",
        ) as f:
            configs = json.loads(f.read())
            config = list(
                filter(lambda item: item["enable"] == 1, configs["projects"])
            ).pop()
            workspace = config["workspace"]
            source = config["source"]
            author = config["author"]
            package = config["package"]
    except FileNotFoundError as ex:
        no_set_file = True
        config_file_path = os.path.join(os.path.expanduser("~"), config_filename)
        shutil.copy(config_filename, config_file_path)
    except KeyError as ex:
        print("{}缺失配置。".format(config_filename))
        raise ex
    if no_set_file:
        print(
            f"""已初始化配置文件至{My_Util.get_color_text(config_file_path, 4)}，请配置后重新运行本程序"""
        )
        return None
    return {"config": config, "workspace": workspace, "source": source, "code_target": config["code_target"]}


def try_get_project_file_path(_config):
    """
    尝试获取工程文件
    """
    project_file_path = os.path.join(_config["workspace"], _config["source"])
    if not os.path.exists(project_file_path):
        shutil.copy(_config["source"], project_file_path)
        print(
            f"""已初始化工程文件至{My_Util.get_color_text(project_file_path,4)}.\n请按照README.md中的教程内容维护工程文件.\n然后重新运行本程序."""
        )
        return None
    return project_file_path


def try_get_conn(db_config):
    """
    获取数据库连接
    """
    return pymysql.connect(
        host=db_config["host"],
        user=db_config["user"],
        password=db_config["password"],
        database=db_config["database"],
        read_timeout=10,
    )


def clear_temp_files(temp_files):
    """
    清理临时文件
    """
    for file in temp_files:
        os.remove(file)


def main():
    _config = get_config()
    if _config is None:
        return
    final_files = ["Input.xlsx", "Output.xlsx", _config["code_target"], "sql"]
    target_dir = os.path.join(_config["workspace"], "target")
    if os.path.exists(target_dir):
        shutil.rmtree(target_dir)
    os.mkdir(target_dir)
    _output = final_files[0]
    _project_file_path = try_get_project_file_path(_config)
    if _project_file_path is None:
        return
    # 复制工程文件到工作空间
    shutil.copy(
        _project_file_path,
        os.path.join(target_dir, _output),
    )
    # 读取工程配置
    project_config = ProjectConfigReader().read_config(
        os.path.join(target_dir, _output)
    )
    temp_files = set()
    datasource = try_get_conn(_config["config"]["db"])
    try:
        for plugin in plugins(_config["config"]):
            if plugin.enable is False:
                plugin.print("已跳过...\n")
                continue
            plugin.print("工作中,请等待...")
            plugin.start_record()
            plugin.set_project_config(project_config)
            if plugin.depend_on_db():
                plugin.set_datasource(datasource)
            _output = plugin.run(target_dir, _output)
            temp_files.add(os.path.join(target_dir, _output))
            _result = plugin.result()
            plugin.end_record()
            plugin.print(
                f"""已处理[{My_Util.get_color_text(_result['processed'],3)}],耗时:{My_Util.get_color_text(round(plugin.end_timestamp - plugin.start_timestamp, 3), 4)}秒\n"""
            )
    except Exception as ex:
        print(ex)
        raise ex
    finally:
        datasource.close()
    shutil.copy(
        os.path.join(target_dir, _output),
        os.path.join(target_dir, final_files[1]),
    )
    clear_temp_files(temp_files)


if __name__ == "__main__":
    main()
